<template>
  <div class="app-container">
    <el-row>
      <el-select
        style="width: 200px; margin-right: 5px"
        v-model="company"
        filterable
        @change="comapyChange"
        placeholder="单位"
      >
        <el-option
          v-for="item in companies"
          :key="item.val"
          :value="item.val"
          :label="item.name"
        >
        </el-option>
      </el-select>

      <el-select v-model="sjSelectVal" placeholder="时间类型">
        <el-option
          v-for="item in sjSelects"
          :key="item.val"
          :label="item.name"
          :value="item.val"
        >
        </el-option>
      </el-select>

      <el-date-picker
        v-model="stime"
        value-format="yyyy-MM-dd"
        type="date"
        placeholder="开始日期"
      >
      </el-date-picker>
      <span style="margin-left: 5px">至</span>
      <el-date-picker
        v-model="etime"
        value-format="yyyy-MM-dd"
        type="date"
        placeholder="结束日期"
      >
      </el-date-picker>

      <el-select
        style="width: 200px; margin-left: 5px"
        v-model="cybf"
        filterable
        placeholder="科室"
      >
        <el-option
          v-for="item in cybfs"
          :key="item.val"
          :value="item.val"
          :label="item.name"
        >
        </el-option>
      </el-select>

      <el-select
        style="margin-left: 5px"
        v-model="selectStatus"
        placeholder="数据状态"
      >
        <el-option-group
          v-for="group in status"
          :key="group.label"
          :label="group.label"
        >
          <el-option
            v-for="item in group.options"
            :key="item.val"
            :label="item.label"
            :value="item.val"
          >
          </el-option>
        </el-option-group>
      </el-select>

      <el-select
        style="margin-left: 5px; width: 250px"
        multiple
        collapse-tags
        v-model="grpSelect"
        placeholder="分组：（可多选，MDC默认）"
      >
        <el-option
          v-for="item in grpSelects"
          :key="item.val"
          :label="item.name"
          :value="item.val"
        >
        </el-option>
      </el-select>

      <el-button @click="search" style="margin-left: 5px" type="danger" round
        >&nbsp;&nbsp;搜索&nbsp;&nbsp;</el-button
      >

      <el-dropdown style="float: right" @command="handleCommand">
        <el-button type="primary" round>
          其他<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="gener-word">分析报告</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-row>

    <el-row>
      <el-table
        :data="
          tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)
        "
        show-summary
         v-loading="loading"
         element-loading-text="加载中..."

        :summary-method="summaries"
        @sort-change="sortChange"
        style="width: 100%"
      >
        <el-table-column type="index" width="50"> </el-table-column>
        <!-- <el-table-column prop="grpinfomdc" sortable label="MDC">
        </el-table-column> -->

        <el-table-column
          v-for="col in grpCols"
          v-bind:key="col.col"
          :prop="col.col"
          sortable
          :label="col.name"
        >
        </el-table-column>
        <el-table-column prop="mdcCount" sortable label="MDC数">
        </el-table-column>

        <el-table-column prop="drgCount" sortable label="DRG数">
        </el-table-column>

        <el-table-column prop="adrgCount" sortable label="ADRG数">
        </el-table-column>

        <el-table-column prop="pCount" sortable label="病例数">
        </el-table-column>
        <el-table-column prop="ingrpCount" sortable label="入组人次">
        </el-table-column>

        <el-table-column
          sortable
          prop="weightAvg"
          :formatter="fmtFixed2"
          label="CMI"
        >
        </el-table-column>

        <el-table-column
          prop="costratioAvg"
          sortable
          :formatter="fmtFixed2"
          label="费用消耗"
        >
        </el-table-column>

        <el-table-column
          prop="bedratioAvg"
          :formatter="fmtFixed2"
          sortable
          label="时间消耗"
        >
        </el-table-column>

        <el-table-column
          prop="zfySum"
          sortable
          :formatter="fmtFixed2"
          label="住院总费用"
        >
        </el-table-column>
        <el-table-column
          prop="zfyAvg"
          :formatter="fmtFixed2"
          sortable
          label="住院平均费用"
        >
        </el-table-column>

        <el-table-column
          prop="benchmarkFeeSum"
          sortable
          :formatter="fmtFixed2"
          label="标准总费用"
        >
        </el-table-column>
        <el-table-column
          prop="benchmarkFeeAvg"
          sortable
          :formatter="fmtFixed2"
          label="标准平均费用"
        >
        </el-table-column>

        <el-table-column prop="deadCount" sortable label="死亡人次">
        </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200, 500, 1000, 10000]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="float: right"
      >
      </el-pagination>
    </el-row>
  </div>
</template>

<style scoped>
.el-select {
  width: 120px;
}
.el-date-editor {
  margin-left: 5px;
  width: 140px;
}
</style>
  <script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { PfmModule } from "@/store/modules/PfmRepo";
import { ConfModule } from "@/store/modules/ConfRepo";
import { time } from "console";
@Component({
  name: "performance-analysis",
})
export default class extends Vue {
  //分组字段

  private grpSelects = [
    {
      name: "MDC",
      val: "grpinfo.mdc",
    },
    {
      name: "病组",
      val: "grpinfo.drg,grpinfo.name",
    },
    {
      name: "ADRG",
      val: "grpinfo.adrg",
    },
    {
      name: "病区",
      val: "cybf",
    },
    {
      name: "住院医生",
      val: "zyys",
    },
    {
      name: "主治医生",
      val: "zzys",
    },
  ];

  private colsMap: Array<any> = [
    {
      col: "grpinfomdc",
      name: "MDC",
    },
    {
      col: "grpinfodrg",
      name: "病组编码",
    },
    {
      col: "grpinfoname",
      name: "病组名称",
    },
    {
      col: "grpinfoadrg",
      name: "ADRG",
    },
  ];

  private grpSelect: any = ["grpinfo.mdc"];

  private sjSelects = [
    {
      name: "出院时间",
      val: "cysj",
    },
    {
      name: "入院时间",
      val: "rysj",
    },
  ];
  private total: number | undefined = 0;
  private pagesize: number | undefined = 10;
  private currentPage: number | undefined = 1;

  private stime: string = this.dateFormat("yyyy-mm-dd", this.getStime());
  private etime: string = this.dateFormat("yyyy-mm-dd", new Date());

  //单位列表
  private companies: Array<any> = [];
  private company = "";

  //出院病房
  private cybfs: Array<any> = [];
  private cybf = "";

  private getStime(): Date {
    var d = new Date();
    d.setMonth(new Date().getMonth() - (<any>window).MyConf.TIMEINTERVAL);
    return d;
  }

  private dateFormat(fmt: string, date: Date) {
    let ret;
    const opt = {
      "y+": date.getFullYear().toString(), // 年
      "m+": (date.getMonth() + 1).toString(), // 月
      "d+": date.getDate().toString(), // 日
      "H+": date.getHours().toString(), // 时
      "M+": date.getMinutes().toString(), // 分
      "S+": date.getSeconds().toString(), // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        var op = (<any>opt)[k];
        fmt = fmt.replace(
          ret[1],
          ret[1].length == 1 ? op : op.padStart(ret[1].length, "0")
        );
      }
    }
    return fmt;
  }

  //获取出院病房
  private async loadCybf() {
    var d = await PfmModule.bf({ cpy: this.company });
    var ls = d.data || [];
    this.cybfs = [
      { name: "选择科室", val: "" },
      ...ls.map((it: string) => ({ name: it, val: it })),
    ];
  }

  private handleSizeChange(val: number) {
    this.pagesize = val;
  }
  private handleCurrentChange(val: number) {
    this.currentPage = val;
  }
  private comapyChange() {
    this.loadCybf();
  }
  private async loadCompanies() {
    var d = await ConfModule.dicChildByCode({ code: "company" });
    this.companies = [{ name: "选择单位", val: "" }, ...d.data];
  }
  //排序
  private sortChange(column: any) {
    let prop = column.prop;
    let order = column.order;
    this.currentPage = 1;
    this.tableData.sort((a: any, b: any) => {
      if (typeof a[prop] == "number") {
        if (order == "ascending") return a[prop] - b[prop];
        else return b[prop] - a[prop];
      } else {
        if (order == "ascending") return a[prop].localeCompare(b[prop]);
        else return a[prop].localeCompare(b[prop]) * -1;
      }
      return 0;
    });
  }
  //保留两位小数
  private fmtFixed2(row: any, column: any, cellValue: Number, index: any) {
    if (cellValue) {
      try {
        return cellValue.toFixed(2);
      } catch (error) {
        return cellValue;
      }
    }
    return cellValue;
  }

  //数据状态

  private status = [
    {
      label: "入组情况",
      options: [
        {
          val: "未入组",
          data: {
            col: "ingrp",
            op: "neq",
            val: "true",
          },
        },
        {
          val: "已入组",
          data: {
            col: "ingrp",
            op: "eq",
            val: "true",
          },
        },
      ],
    },{

      label:'费用结算方式',
      options:[{
        val:'医保&入组',
        data:[
         {
            col: "ingrp",
            op: "eq",
            val: "true",
          },{
            col:'ylfkfs.keyword',
            op:'in',
            val:'01,02'
          }
        ]
      }]
    },
    {
      label: "费用",
      options: [
        {
          val: "高倍率",
          data: {
            col: "grpinfo.costratio",
            op: "gte",
            val: 3,
          },
        },
        {
          val: "低倍率",
          data: {
            col: "grpinfo.costratio",
            op: "lte",
            val: 0.3,
          },
        },
        {
          val: "正常倍率",
          data: [
            {
              col: "grpinfo.costratio",
              op: "gt",
              val: 0.3,
            },
            {
              col: "grpinfo.costratio",
              op: "lt",
              val: 3,
            },
          ],
        },
      ],
    },
  ];

  private selectStatus = "医保&入组";

  private sjSelectVal = this.sjSelects[0].val;
  private tableData = [];

  private loading:boolean=true;

  private async created() {
    //加载单位、出院科室
    this.loadCompanies();
    this.loadCybf();
    this.search();
  }

  private buildCols() {
    //------------>构建动态显示字段 开始<--------
    let cols = (<[]>this.grpSelect)
      .flatMap((it: string) => it.split(","))
      .map((it: string) => it.replace(".", ""));
    this.grpCols = [];
    cols.forEach((it) => {
      //在字段影射表里面找
      var findLs = this.colsMap.filter((it2) => it == it2.col);
      //在动态分组表里面找
      var findLs2 = this.grpSelects.filter((it2) => it == it2.val);
      if (findLs.length > 0) {
        this.grpCols.push(findLs[0]);
      } else if (findLs2.length > 0) {
        this.grpCols.push({ name: findLs2[0].name, col: findLs2[0].val });
      } else {
        //原样显示字段
        this.grpCols.push({ name: it, val: it });
      }
    });
    //-------------->结束<-------------
  }
  //分组动态显示的字段
  private grpCols: Array<any> = [];
  private async search() {

    var timer=setTimeout(() => {
     this.loading=true;
    }, 500);
    this.currentPage = 1;

    this.buildCols();

    //======》条件构造 开始<=============
    //统计入组的信息
    // var where = [{ col: "ingrp", op: "eq", val: "true" }];
    var where: any = [];
    //单位
    if (this.company) {
      where.push({ col: "username.keyword", op: "eq", val: this.company });
    }
    //出院病房
    if (this.cybf) {
      where.push({ col: "cybf.keyword", op: "eq", val: this.cybf });
    }

    //数据状态
    if (this.selectStatus) {
      var sStatus = this.status
        .flatMap((it: any) => it.options)
        .filter((it: any) => it.val == this.selectStatus);
      if (sStatus && sStatus.length > 0) {
        sStatus = sStatus[0].data;
        //判断是否是数组
        if (sStatus instanceof Array) {
          where.push(...sStatus);
        } else where.push(sStatus);
      }
    }
    //======》条件构造 结束<=============
    var grpinfo: any = this.grpSelect;
    grpinfo = grpinfo.join(",");

    var d = await PfmModule.grpls({
      stime: this.stime.replaceAll("-", ""),
      etime: this.etime.replaceAll("-", ""),
      time: this.sjSelectVal,
      grp: grpinfo,
      where: encodeURIComponent(JSON.stringify(where)),
      page: 0,
      size: 10000,
    });
    this.tableData = d.data.ls || [];
    this.total = d.data.ls.length;
    this.sumarryTotal = d.data.total;
    clearTimeout(timer);
    this.loading=false;
    
  }

  private sumarryTotal: any = {};
  //合计
  private summaries(param: any) {
    const { columns, data } = param;

    const sums: Array<any> = [];

    columns.forEach((col: any, index: number) => {
      var prop = col.property;
      if (!prop) {
        sums[index] = "";
      } else if (index == 1) {
        sums[index] = "合计";
      } else {
        var col = prop;
        //如果是统计字段，就不合计
        if (
          this.grpSelects.filter((it) => it.val.replaceAll("\\.", "") == col)
            .length > 0
        ) {
          sums[index] = "";
        } else {
          if (!isNaN(this.sumarryTotal[col])) {
            var val = this.sumarryTotal[col];
            //如果是小数保留两位小数
            if (parseInt(val) != val) {
              val = val.toFixed(2);
            }
            sums[index] = val;
          }
        }
      }
    });

    return sums;
  }

  private handleCommand(cmd: string) {



    switch (cmd) {
      //导出报告
      case "gener-word":
        //PfmModule.generWord({stime:this.stime.replaceAll('-',''),time:this.sjSelectVal,etime:this.etime.replaceAll('-','')})
        var url = `${
          (<any>window)["MyConf"].APISERVICE
        }/pfm/gener-word?stime=${this.stime.replaceAll(
          "-",
          ""
        )}&etime=${this.etime.replaceAll("-", "")}&time=${
          this.sjSelectVal
        }&cpy=${this.company}`;
        console.log(url);
        location.href = url;
        break;
    }
  }
}
</script>